package com.tinckay.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tinckay.common.constant.RegexConstant;
import com.tinckay.common.exception.ServiceException;
import com.tinckay.common.util.MD5Utils;
import com.tinckay.common.util.ShiroUtils;
import com.tinckay.entity.form.FindPasswordForm;
import com.tinckay.entity.po.User;
import com.tinckay.entity.po.UserRole;
import com.tinckay.mapper.UserMapper;
import com.tinckay.service.RedisService;
import com.tinckay.service.UserRoleService;
import com.tinckay.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.Pattern;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Jean
 * @since 2018-10-21
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RedisService redisService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateLoginTime(long userId) {
        baseMapper.updateLoginTime(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addUser(User user, Long[] roles) {
        User byUsername = baseMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getUsername, user.getUsername()));
        User byMobile = baseMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getMobile, user.getMobile()));
        if (null != byUsername) {
            throw new ServiceException("用户名已存在");
        }
        if (null != byMobile) {
            throw new ServiceException("该手机号已被注册");
        }

        user.setCreator(ShiroUtils.getCurrentUser().getName());
        user.setPassword(MD5Utils.encrypt(user.getUsername(), user.getPassword()));
        user.insert();
        setUserRoles(user.getId(), roles);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUsers(Collection<Long> userIds) {
        baseMapper.deleteBatchIds(userIds);
        userRoleService.deleteUserRolesByUserId(userIds);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUser(User user, Long[] roles) {
        user.setPassword(null);
        user.setUsername(null);
        user.updateById();
        userRoleService.deleteUserRolesByUserId(CollectionUtil.toList(user.getId()));
        setUserRoles(user.getId(), roles);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePassword(String password) {
        User user = ShiroUtils.getCurrentUser();
        String newPassword = MD5Utils.encrypt(user.getUsername(), password);
        user.setPassword(newPassword);
        user.updateById();
    }

    @Override
    public User findUserWithRoles(long userId) {
        return baseMapper.findUserWithRoles(userId);
    }

    private void setUserRoles(Long userId, Long[] roles) {
        if (ArrayUtil.isNotEmpty(roles)) {
            for (Long roleId : roles) {
                UserRole ur = new UserRole(userId, roleId);
                ur.insert();
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean findPassword(FindPasswordForm findPasswordForm) {

        String mobilePhone = findPasswordForm.getMobile();
        String validCode = (String) redisService.getValue(mobilePhone);

        if (StrUtil.isBlank(validCode)) {
            throw new ServiceException("验证码已失效或未获取验证码");
        }
        if (!findPasswordForm.getValidCode().equals(validCode)) {
            throw new ServiceException("验证码有误");
        }

        User user = baseMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getMobile, mobilePhone));

        if (null == user) {
            throw new ServiceException("该手机号尚未注册账户");
        }

        String newPassword = MD5Utils.encrypt(user.getUsername(), findPasswordForm.getNewPassword());
        user.setPassword(newPassword);
        redisService.removeKey(mobilePhone);
        return user.updateById();
    }

    @Override
    public List<User> findUserByRoleName(String roleName) {
        return baseMapper.findUserByRoleName(roleName);
    }

}
